package com.study.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;

/**
 * @Author: sjw
 * @Description: json工具类
 * @Date: 2018/6/25 17:16
 */

public class JsonHelper {
    private static final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    public static <T> String objectToJson(T obj) {
        try {
            return gson.toJson(obj);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return obj.toString();
    }

    public static <T> T jsonToObject(String json, Class<T> classType, String pattern) {
        Gson gson = new GsonBuilder().setDateFormat(pattern).create();
        try {
            return gson.fromJson(json, classType);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static <T> T jsonToObject(String json, Class<T> classType) {
        try {
            return gson.fromJson(json, classType);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static <T> T jsonToObject(String json, Type classType) {
        try {
            return gson.fromJson(json, classType);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
